Skip to content

Ajustado services para classe de erros. - #449

Merged
CaffeineIssues merged 8 commits into
developfrom
feature/classes_erros
Aug 10, 2026
Merged

Ajustado services para classe de erros.#449
CaffeineIssues merged 8 commits into
developfrom
feature/classes_erros

Conversation

@Junior-Shyko

@Junior-Shyko Junior-Shyko commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

✅ Descrição do propósito desse Pull Request


🧭 Referência a Issue


❓ O que foi feito para atingir isso?


🏃‍♀️ Tipo de mudança

Marque as opções relevantes:

  • Bug fix (correção de bug)
  • Nova feature (mudança não retrocompatível que adiciona funcionalidade)
  • Mudança de breaking (correção ou feature que faria com que a funcionalidade existente não funcionasse como esperado)
  • Documentação (somente mudanças ou atualizações na documentação)

🕵️ Como foi testado?

  • Critério de aceitação
  • Testes de software (TDD, BDD, UNITÁRIO, INTEGRAÇÃO, E2E)

Checklist: ✔️

  • Meu código segue as diretrizes do projeto
  • Eu fiz um code review com minha equipe
  • Eu comentei meu código, especialmente em áreas de difícil entendimento
  • Eu atualizei a documentação correspondente
  • Testes novos e existentes passaram localmente com minhas alterações

Observação:

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling across document, installment, project, and stage workflows with clearer validation and authorization feedback.
    • Standardized failures from Google Sheets and external mapping services, including safer connection and response error handling.
    • Improved browser and API error responses with appropriate redirects, validation messages, and JSON responses.
    • Added safer handling of external-service details, including protection for sensitive URL query information.
  • Documentation

    • Added guidance for standardized backend and frontend error handling, rollout, verification, and security practices.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The change standardizes application exceptions across services and controllers. It adds structured external-service failures, domain-specific validation and authorization exceptions, centralized JSON or redirect rendering, updated feature tests, and an error-handling implementation plan.

Changes

Exception handling alignment

Layer / File(s) Summary
External service failure classification
app/Exceptions/Integration/ExternalServiceException.php, app/Services/GoogleSheetsService.php, app/Services/MapasClient.php
External service failures now use structured ExternalServiceException instances with service, path, URL, and redacted query metadata.
Domain exception classification
app/Services/Documents/DocumentTypeRegistry.php, app/Services/InstallmentImportService.php, app/Services/NoticeService.php, app/Services/ProjectDocumentService.php, app/Services/ProjectStageService.php, app/Services/ProjectSupervisorService.php, app/Support/Import.php, tests/Feature/Document/DocumentTest.php, tests/Feature/InstallmentImportServiceTest.php, tests/Feature/ProjectStageFlowTest.php
Business-rule, authorization, and stage-transition failures now use dedicated exception classes. Feature tests assert the new exception types.
Controller propagation and rendering
app/Http/Controllers/InstallmentController.php, app/Http/Controllers/ProjectController.php, app/Http/Controllers/ProjectStageController.php, bootstrap/app.php
Controllers now propagate application exceptions or handle AppException through unified reporting. Rendering returns JSON for non-Inertia JSON requests and redirects other requests with errors.
Exception architecture documentation
docs/erros_plan.md
The plan documents the exception hierarchy, centralized rendering, migration status, frontend handling, rollout sequence, and verification checks.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ProjectStageController
  participant ProjectStageService
  participant AppExceptionRenderer
  Client->>ProjectStageController: advance stage
  ProjectStageController->>ProjectStageService: advance
  ProjectStageService-->>ProjectStageController: AppException
  ProjectStageController-->>AppExceptionRenderer: propagate exception
  AppExceptionRenderer-->>Client: JSON response or redirect with errors
Loading

Possibly related PRs

Suggested reviewers: jeff-doliveira1, caffeineissues

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed O título descreve a principal alteração: o uso de classes de erro específicas nos services e componentes relacionados.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/classes_erros

Comment @coderabbitai help to get the list of available commands.

@Junior-Shyko Junior-Shyko changed the title Feature/classes erros Ajustado services para classe de erros. Jul 31, 2026
@Junior-Shyko
Junior-Shyko marked this pull request as draft July 31, 2026 15:20
@Junior-Shyko
Junior-Shyko marked this pull request as ready for review July 31, 2026 18:22

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/Exceptions/Integration/ExternalServiceException.php`:
- Around line 19-26: Update ExternalServiceException::fromFailedResponse so the
explicitly provided $service always remains authoritative when merging context
metadata. Replace the current spread-based merge with an array-union arrangement
that preserves ['service' => $service] even when $context contains a service
key.

In `@app/Http/Controllers/InstallmentController.php`:
- Line 41: Update the exception handling around SpreadsheetImporter::import() in
InstallmentController so InvalidArgumentException is caught before the broader
Throwable handler, preserving and returning its missing-header message instead
of replacing it with the generic error.

In `@app/Services/GoogleSheetsService.php`:
- Line 39: Update both Google Sheets fetch methods, including fetchSheet() and
the method at app/Services/GoogleSheetsService.php lines 219-219, to catch
ConnectionException alongside RequestException and wrap either in
ExternalServiceException; also add ExternalServiceException to fetchSheet()’s
declared exceptions.

In `@app/Services/MapasClient.php`:
- Around line 127-133: The MapasClient failure paths must stop storing
unsanitized upstream data in ExternalServiceException. In
app/Services/MapasClient.php lines 127-133, keep the error message stable using
only safe status and path fields, excluding the response body; at lines 210-214
and 228-229, redact query parameters from download URLs before storing or
reporting failures.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0fa00495-0c94-479c-b623-77d7a7de4445

📥 Commits

Reviewing files that changed from the base of the PR and between ef6cffd and d70459c.

📒 Files selected for processing (16)
  • app/Exceptions/Integration/ExternalServiceException.php
  • app/Http/Controllers/InstallmentController.php
  • app/Http/Controllers/ProjectController.php
  • app/Http/Controllers/ProjectStageController.php
  • app/Services/Documents/DocumentTypeRegistry.php
  • app/Services/GoogleSheetsService.php
  • app/Services/InstallmentImportService.php
  • app/Services/MapasClient.php
  • app/Services/NoticeService.php
  • app/Services/ProjectDocumentService.php
  • app/Services/ProjectStageService.php
  • app/Services/ProjectSupervisorService.php
  • bootstrap/app.php
  • tests/Feature/Document/DocumentTest.php
  • tests/Feature/InstallmentImportServiceTest.php
  • tests/Feature/ProjectStageFlowTest.php

Comment thread app/Exceptions/Integration/ExternalServiceException.php
Comment thread app/Http/Controllers/InstallmentController.php
Comment thread app/Services/GoogleSheetsService.php
Comment thread app/Services/MapasClient.php Outdated
Junior-Shyko and others added 2 commits August 3, 2026 14:35
…449)

Registra no inventário/status da migração os ajustes feitos após o review:
Import::validateRequiredColumns migrado para BusinessRuleException, e
GoogleSheetsService/MapasClient refinados (captura de ConnectionException e
sanitização de dados sensíveis nas mensagens de exceção).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@Junior-Shyko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (1)
docs/erros_plan.md (1)

41-41: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Adicione a linguagem ao bloco Markdown.

O markdownlint reporta MD040 na linha 41. Use ```text ou ```tree para remover o aviso.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/erros_plan.md` at line 41, Atualize o bloco de código Markdown na seção
correspondente de docs/erros_plan.md, adicionando um identificador de linguagem
após as três crases de abertura, como text ou tree, para eliminar o aviso MD040
do markdownlint.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/erros_plan.md`:
- Around line 30-37: Atualize a descrição de ExternalServiceException no
documento para classificá-la como exceção de integração ou técnica, substituindo
a referência atual a exceção de domínio e mantendo consistente com a hierarquia
em app/Exceptions/Integration/.
- Around line 154-164: Alinhe o plano para usar uma única lista e contagem de
controllers: corrija o título e a tabela que enumeram os controllers com catch,
e remova ou ajuste as referências posteriores nas linhas 191 e 289 para não
incluir MonitoringController, NotificationController e PaymentController se
permanecerem fora do escopo. Preserve FormalizationController fora da migração
conforme indicado.
- Line 9: Atualize o plano em docs/erros_plan.md para distinguir claramente
etapas históricas já concluídas do trabalho ainda pendente: marque o rollout
como histórico ou remova etapas concluídas, incluindo a fundação e migrações
mencionadas nas seções próximas às linhas 184-195 e 282-291. Preserve apenas
ações realmente futuras e deixe explícito o estado atual do plano.
- Around line 110-122: Atualize a documentação do handler de renderização para
refletir o comportamento de bootstrap/app.php: use JSON apenas quando
expectsJson() e não houver X-Inertia; nos demais casos, retorne
back()->withErrors(...), removendo o fallback implícito. Corrija também as
referências nas seções associadas para documentar que
ProjectStageController::return() é uma exceção e preserva back()->with('error',
...), mantendo o fluxo esperado por ReturnProcessModal.vue.

---

Nitpick comments:
In `@docs/erros_plan.md`:
- Line 41: Atualize o bloco de código Markdown na seção correspondente de
docs/erros_plan.md, adicionando um identificador de linguagem após as três
crases de abertura, como text ou tree, para eliminar o aviso MD040 do
markdownlint.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ec7bfce1-d808-4f40-936a-63872ca783cc

📥 Commits

Reviewing files that changed from the base of the PR and between d70459c and 6108ebd.

📒 Files selected for processing (5)
  • app/Exceptions/Integration/ExternalServiceException.php
  • app/Services/GoogleSheetsService.php
  • app/Services/MapasClient.php
  • app/Support/Import.php
  • docs/erros_plan.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • app/Exceptions/Integration/ExternalServiceException.php
  • app/Services/MapasClient.php
  • app/Services/GoogleSheetsService.php

Comment thread docs/erros_plan.md Outdated
Comment thread docs/erros_plan.md
Comment thread docs/erros_plan.md
Comment thread docs/erros_plan.md Outdated
…bbit

- Deixa claro que o doc virou registro histórico + checklist (partes já
  implementadas, não mais uma proposta em aberto).
- Reclassifica ExternalServiceException como exceção técnica/integração
  (estava descrita como "de domínio", contradizendo a hierarquia em
  app/Exceptions/Integration/).
- Sincroniza o exemplo do handler de bootstrap/app.php com a implementação
  real (ordem expectsJson/X-Inertia) e documenta a exceção do
  ProjectStageController::return() que preserva back()->with('error', ...).
- Corrige contagem/lista de controllers (5, não 6) e remove
  Monitoring/Notification/Payment da lista de trabalho restante, já que
  não têm catch a migrar.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@Junior-Shyko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/erros_plan.md`:
- Line 287: Atualize o passo histórico 3 em docs/erros_plan.md para alinhar seu
escopo com a seção 3.1: marque as referências a SpreadsheetImportService e
PUMLGeneratorService como substituídas ou remova-as, mantendo o passo limitado a
GoogleSheetsService e MapasClient. Preserve a indicação de que os demais
controllers possuem o escopo descrito na linha sobre InstallmentController,
ProjectController, UserController e OpeningController.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 01c7ed56-05fb-4ca4-ba38-9de7bfaa9842

📥 Commits

Reviewing files that changed from the base of the PR and between 6108ebd and 943e569.

📒 Files selected for processing (1)
  • docs/erros_plan.md

Comment thread docs/erros_plan.md
…ação

Passo 3 ainda citava SpreadsheetImportService e PUMLGeneratorService como
alvo de ExternalServiceException, mas a seção 3.1 já os marca como fora de
escopo. Restringe o passo a GoogleSheetsService e MapasClient.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@Junior-Shyko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/erros_plan.md`:
- Line 286: Before removing the legacy InvalidArgumentException renderer from
bootstrap/app.php, audit references across code, tests, and documentation
separately. Update the InvalidArgumentException throw in SyncProjectFilesJob and
preserve or revise the test asserting a 422 response, then verify no runtime
dependencies remain before deleting the handler.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 36d2dc88-3b15-4a1c-b492-d4bf3247c1da

📥 Commits

Reviewing files that changed from the base of the PR and between 943e569 and 03aecca.

📒 Files selected for processing (1)
  • docs/erros_plan.md

Comment thread docs/erros_plan.md
@CaffeineIssues
CaffeineIssues merged commit aaa0ce7 into develop Aug 10, 2026
4 checks passed
@CaffeineIssues
CaffeineIssues deleted the feature/classes_erros branch August 10, 2026 12:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants